from keras.datasets import mnist
from keras import models
from keras import layers
from keras.utils import to_categorical

model = models.Sequential()
model.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
model.add(layers.Dense(10, activation='softmax'))

model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
# 加载数据
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 转换数据为神经网络可接受的结构
train_images = train_images.reshape((60000, 28 * 28))
# 将数据范围约束到0-1之间
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
# one_hot encoding(独热编码)
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

# fit训练数据
model.fit(train_images, train_labels, epochs=5, batch_size=128)
# evaluate评估模型，在测试集上评估
test_loss, test_acc = model.evaluate(test_images, test_labels)
print("-" * 50)
print('test_loss:', test_loss)
print('test_acc:', test_acc)

# loss: 0.0374 - acc: 0.9889
# test_loss: 0.0637069644213
# test_acc: 0.9823